package main

import (
	"fmt"

	"log"

	"database/sql"

	"os"

	"time"

	"github.com/fatih/color"
	_ "github.com/go-sql-driver/mysql"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

//func MysqlDb() *sql.DB {

//}

const MONGO_URL = "10.8.2.29:30000"

func Session() *mgo.Session {
	session, err := mgo.Dial(MONGO_URL)
	if err != nil {
		color.Red("连接mongodb 出错")
		os.Exit(2)
	}
	session.SetMode(mgo.Monotonic, true)
	session.SetBatch(10)
	return session
}
func FetchMongoData(Session *mgo.Session) {
	session := Session

	db := session.DB("database")
	collection := db.C("questions")
	dataTime := time.Date(2004, 7, 14, 0, 0, 0, 0, time.UTC)
	iter := collection.Find(bson.M{"postDate": bson.M{"$lte": dataTime}}).Iter()
	var data map[string]interface{}
	i := 1
	for iter.Next(&data) {

		fmt.Println(data["postDate"])
		fmt.Printf("%V\n", data["postDate"])

		if i == 5 {
			break
		}
		i++
	}

}
func main() {
	db, err := sql.Open("mysql", "wenwo:wenwo@wenwo@tcp(10.8.2.17:3306)/wenwo")
	if err != nil {
		log.Fatalf("Open database error: %s\n", err)
	}

	//	defer db.Close()
	fmt.Println(db.Ping())
	row, err := db.Query("select * from netizens_views")
	//	defer row.Close()
	columns, err := row.Columns()
	log.Println(columns)
	//	row.Close()
	//	db.Close()
	session := Session()
	defer session.Clone()
	FetchMongoData(session)

}
